import classnames from "classnames";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { View } from "@tarojs/components";

import "./index.scss";

interface DrawerProps {
  className?: string;
  open: boolean;
  mask?: boolean;
  children?: React.ReactNode;
  onClose?: () => void;
  // @default 230px  抽屉宽度
  width?: React.CSSProperties["width"];
  // 是否从右侧滑出 @default false
  right?: boolean;
}

export const Drawer: React.FC<DrawerProps> = ({
  className,
  open,
  mask = true,
  children,
  onClose,
  right = false,
  width = "",
}) => {
  const [_animShow, setAnimShow] = useState(false);
  const [_open, setOpen] = useState(false);

  const $$onCloseRef = useRef(onClose);
  $$onCloseRef.current = onClose;

  const animShow = useCallback(() => {
    setOpen(true);
    setTimeout(() => {
      setAnimShow(true);
    }, 200);
  }, []);

  const animHide = useCallback(() => {
    setAnimShow(false);
    setTimeout(() => {
      setOpen(false);
      $$onCloseRef.current && $$onCloseRef.current();
    }, 300);
  }, []);

  useEffect(() => {
    if (open) {
      animShow();
    } else {
      animHide();
    }
  }, [open, animShow, animHide]);

  const containerClass = classnames(
    "at-drawer",
    {
      "at-drawer--show": _animShow,
      "at-drawer--right": right,
      "at-drawer--left": !right,
    },
    className
  );
  const maskStyle = {
    display: mask ? "block" : "none",
    opacity: _animShow ? 1 : 0,
  };
  const listStyle = {
    width,
    transition: _animShow ? "all 225ms cubic-bezier(0, 0, 0.2, 1)" : "all 195ms cubic-bezier(0.4, 0, 0.6, 1)",
  };
  if (_open) {
    return (
      <View className={containerClass}>
        <View className="at-drawer__mask" style={maskStyle} onClick={animHide}></View>
        <View className="at-drawer__content" style={listStyle}>
          {children}
        </View>
      </View>
    );
  }
  return <View></View>;
};
